package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";
    @Override
    public CartItemVo addCartItem(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();


        //  获取购物车中商品
        String res = (String) getCartOps().get(skuId.toString());
        // 没有该商品 ，则新增
        if (StringUtils.isEmpty(res)) {
            CartItemVo cartItemVo = new CartItemVo();
            // 远程查询商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {

                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });


                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(data.getSkuDefaultImg());
                cartItemVo.setTitle(data.getSkuTitle());
                cartItemVo.setSkuId(data.getSkuId());
                cartItemVo.setPrice(data.getPrice());
            }, executor);


            // 远程查询商品属性信息
            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                List<String> skuAttr = productFeignService.getSkuAttr(skuId);
                cartItemVo.setSkuAttrValues(skuAttr);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrTask).get();

            String jsonString = JSON.toJSONString(cartItemVo);

            cartOps.put(skuId.toString(),jsonString);

            return cartItemVo;
        }else {
            // 存在则修改数量
            CartItemVo cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),jsonString);
            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartRedis(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(o, CartItemVo.class);
    }

    @Override
    public CartVo getCart() throws InterruptedException, ExecutionException {
        // 1 判断是否登录
        UserInfo userInfo = CartInterceptor.threadLocal.get();
        String tempCart = CART_PREFIX + userInfo.getUserKey();
        String userCart = CART_PREFIX + userInfo.getUserId();

        CartVo cartVo = new CartVo();
        if (userInfo.getUserId() == null) {
            // 没登录
            List<CartItemVo> cartList = getCartList(tempCart);
            cartVo.setItems(cartList);
            return cartVo;
        }
        else {
            // 一登录
            // 要合并购物车
            List<CartItemVo> cartList = getCartList(tempCart);
            if (cartList != null && !cartList.isEmpty()) {
                for (CartItemVo cartItemVo : cartList) {
                    addCartItem(cartItemVo.getSkuId(),cartItemVo.getCount());
                }
            }
            List<CartItemVo> userCartList = getCartList(userCart);
            cartVo.setItems(userCartList);
            // clear temp shop
            redisTemplate.delete(tempCart);
            return cartVo;
        }
    }

    @Override
    public void updateCheckCart(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String data = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(data, CartItemVo.class);
        if (cartItemVo != null) {
            cartItemVo.setCheck(checked == 1);
        }
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public void updateNumCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String data = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(data, CartItemVo.class);
        if (cartItemVo != null) {
            cartItemVo.setCount(num);
        }
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public void deleteCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        Long delete = cartOps.delete(skuId.toString());
    }

    public List<CartItemVo> getCartList(String key){
        ArrayList<CartItemVo> list = new ArrayList<>();
        // 没登录
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(key);
        List<Object> values = cartOps.values();
        for (Object value : values) {
            CartItemVo cartItemVo = JSON.parseObject(value.toString(), CartItemVo.class);
            list.add(cartItemVo);
        }
        return list;
    }

    public BoundHashOperations<String, Object, Object> getCartOps(){
        UserInfo userInfo = CartInterceptor.threadLocal.get();
        String cartKey = CART_PREFIX;
        if (userInfo.getUserId() != null) {
            // 登录
            cartKey = cartKey + userInfo.getUserId();
        }else {
            cartKey = cartKey + userInfo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
